package com.example.mykotilin.navigation1.listscreen

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.mykotilin.R


class LeaderFragment : Fragment() {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_leader, container, false)
        val viewAdapter = MyAdapter(Array(10) { "Person %${it + 1}" })
        view.findViewById<RecyclerView>(R.id.leaderboard_list).run {
            setHasFixedSize(true)
            adapter = viewAdapter
        }
        return view
    }

}

class MyAdapter(private val myDataSet: Array<String>) :
    RecyclerView.Adapter<MyAdapter.ViewHolder>() {


    companion object {
        const val USERNAME_KEY = "userName"
    }

    class ViewHolder(val item: View) : RecyclerView.ViewHolder(item)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.list_view_item, parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.item.findViewById<TextView>(R.id.user_name_text).text = myDataSet[position]
        holder.item.findViewById<ImageView>(R.id.user_avatar_image)
            .setImageResource(listOfAvatars[position % listOfAvatars.size])
        holder.item.setOnClickListener {
            val bundle = bundleOf(USERNAME_KEY to myDataSet[position])
            holder.item.findNavController().navigate(R.id.action_leader_to_userprofile, bundle)
        }
    }

    override fun getItemCount() = myDataSet.size
}

private val listOfAvatars = listOf(
    R.drawable.avatar_1_raster,
    R.drawable.avatar_2_raster,
    R.drawable.avatar_3_raster,
    R.drawable.avatar_4_raster,
    R.drawable.avatar_5_raster,
    R.drawable.avatar_6_raster
)